import { Button, Input, Table, Form, Popover, Select, Card, Pagination } from 'antd'
import React, { useState } from 'react'
import CustomBreadcrumb from '@/components/CustomBreadcrumb'
import { useRequest } from 'ahooks'
import { requestWrapper } from '@/utils/request'
import { withRouter } from 'react-router-dom'
import newAPI from '@/services/new'
import { TYPE, STATE } from '@/const'
import newFormat from '@/utils/format.js'
import './styles.scss'
const { Option } = Select
const { Search } = Input
const EditPopover = ({ getFieldDecorator, children, submit, newId }) => {
    const [visible, setVisible] = useState(false)
    const [loading, setLoading] = useState(false)
    return (
        <Popover
            placement='left'
            visible={visible}
            onVisibleChange={visible => setVisible(visible)}
            content={
                <div className='role_form'>
                    <h4>修改状态</h4>
                    <Form
                        onSubmit={() => {
                            submit(newId)
                            setLoading(true)
                            setTimeout(() => {
                                setLoading(false)
                                setVisible(false)
                            }, 1000)
                        }}>
                        <Form.Item>
                            {getFieldDecorator('state', {})(
                                <Select style={{ width: 120 }}>
                                    <Option value='released'>已发布</Option>
                                    <Option value='audit'>待审核</Option>
                                    <Option value='deleted'>已禁用</Option>
                                </Select>
                            )}
                            <Button type='primary' htmlType='submit' style={{ marginLeft: '20px' }} loading={loading}>
                                确认
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
            }
            trigger='click'
            destroyTooltipOnHide={true}
            visible={visible}
            onVisibleChange={visible => setVisible(visible)}>
            {children}
        </Popover>
    )
}
const App = props => {
    const [showList, setShowList] = useState([])
    const [q, setQ] = useState('')
    const [role] = useState(JSON.parse(localStorage.getItem('myInfo')).role || 'normal')
    const { getFieldDecorator } = props.form

    const { data: newList, run: getAllNewList, refresh: refreshAll } = useRequest(
        ({ page }) =>
            requestWrapper(newAPI.list.bind(null, { pageSize: 10, q, page: page }), {
                // autoSuccess: true,
            }),
        {
            formatResult: data => data || [],
            defaultParams: [{ page: 1 }],
            manual: role === 'normal',
            onSuccess: () => {
                newList.list.map(value => {
                    value.createAt = newFormat(value.createAt)
                    return value
                })
                setShowList(newList.list)
            }
        }
    )
    const { data: relList, run: getRelNewList, refresh: refreshRel } = useRequest(
        ({ page }) =>
            requestWrapper(newAPI.relNews.bind(null, { pageSize: 10, q, page: page }), {
                // autoSuccess: true,
            }),
        {
            formatResult: data => data || [],
            defaultParams: [{ page: 1 }],
            manual: role === 'admin',
            onSuccess: () => {
                relList.list.map(value => {
                    value.createAt = newFormat(value.createAt)
                    return value
                })
                setShowList(relList.list)
            }
        }
    )

    const getNewList = ({ page }) => {
        role === 'normal' ? getRelNewList({ page: page }) : getAllNewList({ page: page })
    }
    const refresh = () => {
        role === 'normal' ? refreshRel() : refreshAll()
    }

    const { run: updateState } = useRequest(
        ({ newIds, state }) =>
            requestWrapper(newAPI.updateState.bind(null, { ids: newIds, state }), {
                autoSuccess: true
            }),
        {
            manual: true,
            onSuccess: () => {
                refresh()
            }
        }
    )
    const toDetail = newId => {
        console.log(props)
        props.history.push({
            pathname: '/news/new-content',
            search: `?newId=${newId}`,
            state: { newId: newId }
        })
    }

    const submit = newId => {
        props.form.validateFields((err, values) => {
            if (!err) {
                values.newIds = [newId]
                console.log(values)
                updateState(values)
            }
        })
    }

    const [columns] = useState([
        {
            width: 270,
            title: '创建时间',
            dataIndex: 'createAt'
        },
        {
            title: '标题',
            dataIndex: 'title'
        },
        {
            title: '作者',
            dataIndex: 'userName'
        },

        {
            width: 100,
            title: '类型',
            render: (text, record) => TYPE[record.label]
        },
        {
            width: 100,
            title: '状态',
            dataIndex: 'state',
            render: (text, record) => <span className={record.state}>{STATE[record.state]}</span>,
            filters: [
                {
                    text: '待审核',
                    value: 'audit'
                },
                {
                    text: '已发布',
                    value: 'released'
                },
                {
                    text: '已禁用',
                    value: 'deleted'
                }
            ],
            onFilter: (value, record) => record.state.indexOf(value) === 0
        },
        {
            title: '操作',
            render: (text, record) => (
                // this.setState()
                <span>
                    {role === 'normal' || (
                        <EditPopover
                            newId={record.id}
                            getFieldDecorator={getFieldDecorator}
                            submit={submit}
                            children={<a>修改状态</a>}></EditPopover>
                    )}
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <a onClick={() => toDetail(record.id)}>查看详情</a>
                </span>
            )
        }
    ])

    const cardTitle = () => {
        return (
            <div>
                <span className='title'>新闻列表</span>
                <Search
                    className='list_search'
                    placeholder='input search text'
                    onChange={v => {
                        setQ(v.target.value)
                    }}
                    onSearch={() => getNewList({ page: 1 })}
                    style={{ width: 600 }}
                />
            </div>
        )
    }

    return (
        <div className='newList' style={{ minWidth: '1200px' }}>
            <div>
                <CustomBreadcrumb arr={['多级导航']}></CustomBreadcrumb>
            </div>
            <Card type='inner' title={cardTitle()} className='card'>
                <Table pagination={false} dataSource={showList} columns={columns} rowKey={items => items.id}></Table>
            </Card>
            <Pagination
                // hideOnSinglePage={true}
                defaultCurrent={1}
                pageSize={10}
                total={role === 'admin' ? newList && newList.total : relList && relList.total}
                onChange={v => {
                    getNewList({ page: v })
                }}
            />
        </div>
    )
}
export default withRouter(Form.create()(App))
